import React, { Component } from "react";
import { StyleSheet, Text, View, TouchableOpacity, } from "react-native";
import NavigationBar from 'react-native-navbar-plus';
import ViewUtil from "../util/ViewUtil";
import { WebView } from 'react-native-webview';
import FontAwesome from 'react-native-vector-icons/FontAwesome'
import NavigationUtil from "../navigator/NavigationUtil";
import { isIPhoneX } from 'react-native-isiphonex-device'
import BackPressComponent from "../common/BackPressComponent";
import FavoriteDao from "../expand/dao/FavoriteDao";
import { connect } from "react-redux";
import SafeAreaViewPlus from 'react-native-safe-area-plus'
const TRENDING_URL = 'https://github.com/';
const THEME_COLOR = '#678'
class WebViewPage extends Component {
    constructor(props) {
        super(props)
        // 从导航器里面取出参数
        // this.params = this.props.navigation.state.params;
        this.params = this.props.route.params
        const { title, url } = this.params
        this.state = {
            title: title,
            url:url,
            canGoBack: false,
        }
        this.backPress = new BackPressComponent({ backPress: () => this.onBackPress() });
    }

    componentDidMount() {
        this.backPress.componentDidMount();
    }

    componentWillUnmount() {
        this.backPress.componentWillUnmount();
    }

    onBackPress() {
        this.onBack();
        return true
    }
    onBack() {
        // 如果能跳转到上一级,就跳转到上一级
        if (this.state.canGoBack) {
            this.webView.goBack();
        } else {
            NavigationUtil.goBack(this.props.navigation);
        }

    }

    onNavigationStateChange(navState) {
        this.setState({
            canGoBack: navState.canGoback,
            url: navState.url,
        })
    }
    render() {
        const {theme:{themeColor} ={}} =this.props;
        let navigationBar = <NavigationBar
            title={this.state.title}
            style={{ backgroundColor: themeColor }}
            leftButton={ViewUtil.getLeftBackButton(() => this.onBackPress())}
        />
        return (
            <SafeAreaViewPlus topColor={themeColor}>
                {navigationBar}
                <WebView
                    ref={webView => this.webView = webView}
                    startInLoadingState={true}
                    onNavigationStateChange={e => this.onNavigationStateChange(e)}
                    source={{ uri: this.state.url }}
                />
            </SafeAreaViewPlus>
        )
    }
}

const mapStateToProps = state => ({
    theme: state.theme.theme
})

export default connect(mapStateToProps, null)(WebViewPage);
const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginTop: isIPhoneX ? 30 : 0
    }
})